import React, {Component} from 'react';
import {
	ActivityIndicator,
	Alert,
	Dimensions,
	FlatList,
	Image,
	RefreshControl,
	StyleSheet,
	Text,
	TextInput,
	TouchableOpacity,
	View,
} from 'react-native';
import SideMenu from 'react-native-side-menu';
import MeterBooksSideMenu from './MeterBooksSideMenu';
import axiosInstance from './utils/request';

const image =require('../img/menu.png')


let rows=20;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数
let {width,height} = Dimensions.get('window');

export default class CustInfoScene extends Component {


	gotoScannerScreen = () => {
    	const {navigate} = this.props.navigation;
        navigate('ScannerScreen', {page:'CustInfoEditScene'});
    }

    constructor(props) {
    	super(props);
    	this.toggle = this.toggle.bind(this);
		this.SelectMenuItemCallBack = this.SelectMenuItemCallBack.bind(this);
		this.state = {
			isOpen: true,
			isConnected: null,
			page:1,
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: "",
            dataArray: [],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
	 	};
  	}



	/*
		因为服务端modified字段代表的是时间戳，所以Max(anchor)表示客户端最近一次同步的时间，如果存在服务端modified > Max(anchor),
		说明服务端需要向客户端同步数据。
	*/
	fetchData(){
		let custName=this.state.custName;
		let bookId=this.state.bookId;
		let URL=global.server.url+'/custInfo/selectListPageByBookId';
		if(custName){
			page=1;
		}else{
			page=this.state.page;
		}
		axiosInstance.post(URL,
			{
				bookId:bookId,
				custName:custName,
				pageVO:{
					page:page,
					rows:rows
				}
			}
		)
        .then(res => {
			let datas = [];
			let count=res.records.length;
			totalPage=res.pages;
			datas = datas.concat(res.records);
            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            let i = itemNo;
            datas.map(function (item) {
            	dataBlob.push({
                	key: i,
                    custCode:item.custCode,
                    custName:item.custName,
					tel:item.tel,
					custTypeName:item.custTypeName,
					address:item.address
                })
                i++;
            });
            itemNo = i;
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }

            this.setState({
                //复制数据源
            	//  dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray.concat( dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				count:count,
            });
            datas = null;//重置为空
            dataBlob = null;
        })
        .catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	shouldComponentUpdate() {
        return true
    }

    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()
    }

	//加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _keyExtractor = (item, index) => index;

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

	_onChangeText(text) {
		if (text) {
			this.setState({
				custName: text,
				dataArray:[]
			})  //实时变化值
			clearTimeout(this.settimeId);       //如搜索的内容变化在1秒之中，可以清除变化前的fetch请求，继而减少fetch请求。但不能中断fetch请求
			this.settimeId = setTimeout(() => {
			this.fetchData();
		  }, 1000);                                      //让每次要进行fetch请求时先延迟1秒在进行
		  	console.log("sheng chen id:" + this.settimeId);
		} else {
			this.setState({custName: '' })
		}
	}

    //返回itemView
    _renderItemView({item}) {
		//这里返回的就是每个Item
        return (
            <TouchableOpacity activeOpacity={0.5}  onPress={() => {
                    this.props.navigation('CostMasterScene', {custCode:item.custCode})
                }}>
                <View style={styles.items}>
                    <Text style={{marginTop: 5,marginLeft:5, fontSize: 15}}>{item.custName}[{item.custCode}]</Text>
					<View style={styles.rowTextContainer}>
						<Text></Text>
					</View>
                </View>
            </TouchableOpacity>
        )
    }

	//渲染分割线
    _renderSeparator=(sectionID,rowID) =>{
        var style = {
            height:1,
            backgroundColor:"#CCCCCC"
        };
        return(
            <View style={style} key={sectionID+rowID}></View>
        )
    }

    toggle() {
		this.setState({
		  isOpen: !this.state.isOpen,
		});
    }

  	updateMenuState(isOpen) {
		this.setState({ isOpen });
  	}

	//组件挂载完成后执行的方法
    componentDidMount(){
    	this.props.navigation.setOptions({
			title:'客户管理'
		})
		this.props.navigation.setParams({ gotoScannerScreen: this.gotoScannerScreen });
		//检测网络是否连接

        //组件挂载后开始下载数据
        this.fetchData();
    }

	//点击侧边栏的按钮，回调此函数，关闭menu
	SelectMenuItemCallBack = item =>{
		this.setState(
			{
				isOpen:!this.state.isOpen,
				bookId:item.bookId,
				bookName:item.bookName
			},()=>{this.searchData()}
		)
	}

	searchData(){
		this.setState({
            dataArray:[]
        });
		this.fetchData();
    }

	renderData() {
		const menu = <MeterBooksSideMenu onSelectMenuItem={this.SelectMenuItemCallBack} />;
		return (
				<SideMenu
					menu={menu}
					isOpen={this.state.isOpen}
					onChange={isOpen => this.updateMenuState(isOpen)}
					openMenuOffset={0.90*width}//侧边栏的宽度
					disableGestures={false}
				    >
					<View style={styles.container}>
						<View style={{ paddingRight: 15, paddingLeft: 40, marginTop: 5 }}>
							<View style={{ height: 40, backgroundColor: "#fff", borderRadius: 10, paddingLeft: 25, flexDirection: 'row', alignItems: 'center' }} >
							  <Image source={require('../img/search.png')} style={{ width: 25, height: 20 }}></Image>
							  <TextInput underlineColorAndroid="transparent" placeholder="请输入客户名称搜索" style={{ marginLeft: 10, width: 200 }}
								onChangeText={this._onChangeText.bind(this)}
								value={this.state.custName}
								ref="keyWordInput"
								onSubmitEditing={() => { this.refs.keyWordInput.blur() }}>
							  </TextInput>
							  <TouchableOpacity onPress={this.searchData.bind(this)} style={styles.searchView}>
								<Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
							  </TouchableOpacity>
						   </View>
						</View>
						<FlatList
							data={this.state.dataArray}
							renderItem = {({item}) =>
								<TouchableOpacity activeOpacity={0.5} underlayColor='red' onPress={() => {
										this.props.navigation.navigate('CustInfoEditScene', {custCode:item.custCode,custName:item.custName})
									}}>
									<View style={styles.textMainStyle}>
										<Text style={styles.margin}>客户名称：{item.custName}</Text>
										<Text style={styles.margin}>客户编号：{item.custCode}</Text>
										<Text style={styles.margin}>用户类型：{item.custTypeName}</Text>
										<Text style={styles.margin}>联系电话：{item.tel}</Text>
										<Text style={styles.margin}>详细地址：{item.address}</Text>
									</View>
								</TouchableOpacity>
							}
							ListFooterComponent={this._renderFooter.bind(this)}
							onEndReached={this._onEndReached.bind(this)}
							onEndReachedThreshold={0.1}
							keyExtractor={this._keyExtractor}
							//为刷新设置颜色
							refreshControl={
								<RefreshControl
									refreshing={this.state.isRefreshing}
									onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
									colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
									progressBackgroundColor="#ffffff"
								/>
							}
						/>
						<View style={styles.bottomStyle}>
							<Text>
								&nbsp;{this.state.bookName}
							</Text>
							<Text>
								用户数:{this.state.count}
							</Text>
						</View>
					</View>
					<TouchableOpacity onPress={this.toggle} style={styles.button}>
						<Image
							source={image}
							style={{ width: 32, height: 32 }}
						/>
					</TouchableOpacity>
				</SideMenu>
        );
	}

	render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
    	if (this.state.page>1){
            this.fetchData();
        }
    }
}

const styles = StyleSheet.create({
	button: {
		position: 'absolute',
		top: 3,
		padding: 5,
	},
	textMainStyle: {
		flex: 1,
		backgroundColor: '#F5F5F5',
		padding: 10,
		paddingVertical:10,
		marginLeft: 5,
		marginRight: 5,
		marginVertical: 3,
		borderColor: '#dddddd',
		borderStyle: null,
		borderWidth: 0.5,
		borderRadius: 2,
		shadowColor: 'gray',    // 设置阴影
		shadowOffset: {width:0.5, height: 0.5},
		shadowOpacity: 0.4,   // 透明度
		shadowRadius: 1,
		elevation:2   //   高度，设置Z轴，可以产生立体效果
	},
	bottomStyle:{
		fontSize:16,
		marginTop:5,
		marginRight:10,
		fontWeight:"bold",
		flexDirection:'row',
		justifyContent:'space-between',
		width:width - 10,
	},
	container: {
		flex: 1,
		backgroundColor: '#F5FCFF',
	},
	margin:{
	  fontWeight:"bold",
	}
});
